package com.suxin.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Classname WTest
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/12/27 19:57
 * @Created by ASUS
 */
public class RWTest {

    public static void main(String[] args) throws Exception{

        FileOutputStream fileOutputStream = new FileOutputStream("f:\\test1.txt");
        FileInputStream fileInputStream = new FileInputStream("f:\\test.txt");

        FileChannel outputStreamChannel = fileOutputStream.getChannel();
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer rBuffer = ByteBuffer.allocate(1024);

        while (channel.read(rBuffer) != -1) {
            rBuffer.flip();
            outputStreamChannel.write(rBuffer);
            rBuffer.clear();
        }
        outputStreamChannel.close();
        fileInputStream.close();
        fileOutputStream.close();
    }

    private static void test01() throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("f:\\test.txt");

        FileChannel channel = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        byteBuffer.put("hello 魏小雨！".getBytes());

        byteBuffer.flip();

        channel.write(byteBuffer);

        channel.close();

        fileOutputStream.close();

//        读
        FileInputStream fileInputStream = new FileInputStream("f:\\test.txt");

        FileChannel inputStreamChannel = fileInputStream.getChannel();

        ByteBuffer rBuffer = ByteBuffer.allocate(1024);

        inputStreamChannel.read(rBuffer);

        rBuffer.flip();

        System.out.println("读取的数据--->" + new String(rBuffer.array()));

        inputStreamChannel.close();
        fileInputStream.close();
    }

}